package com.lx.zookeeper;

import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Description:
 * Copyright:   Copyright (c)2019
 * Company:     zefu
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2021-11-25 15:55:25
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2021-11-25     张李鑫                     1.0         1.0 Version
 */
public class ZookeeperUtils {
    private static ZooKeeper zk;

    /**
     * zk有根目录的概念 可以
     */
    private static String zkUrl = "127.0.0.1:2181/zkTest";

    private static Logger logger = LoggerFactory.getLogger(ZookeeperUtils.class);

    private static DefaultWatch defaultWatch = new DefaultWatch();

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static ZooKeeper getZk() {
        try {
            zk = new ZooKeeper(zkUrl, 1000, defaultWatch);
            //提供set方法 把countDownLatch设置进去 只有在那边成功了 线程才会继续运行  否则阻塞在这里
            defaultWatch.setCountDownLatch(countDownLatch);
            countDownLatch.await();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("create zk error");
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error(" countDownLatch error");
        }

        return zk;
    }
}
